import SearchTablePage, { SearchTablePageRefType } from '@/components/SearchTablePage';
import { PERMISSION_KEY_MENU } from '@/constants';
import {
  addMenu,
  deleteMenuById,
  getMenuById,
  getMenuList,
  getMenuTree,
  updateMenu,
} from '@/services/system/menu';
import { findMenuPath } from '@/utils/menuUtils';
import { checkRespSuccessful } from '@/utils/serviceUtils';
import {
  ModalForm,
  ProFormSelect,
  ProFormText,
  ProFormTreeSelect,
} from '@ant-design/pro-components';
import { Access, useAccess, useModel } from '@umijs/max';
import { Button, message } from 'antd';
import { useRef, useState } from 'react';

const Menu: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  // 权限控制
  const access = useAccess();
  const [modalOpen, setModalOpen] = useState(false);
  const searchTablePageActionRef = useRef<SearchTablePageRefType>(null);
  return (
    <>
      <SearchTablePage<API.MenuTreeNode>
        tableName="菜单"
        getRowById={getMenuById}
        updateRow={updateMenu}
        addRow={addMenu}
        deleteRowById={deleteMenuById}
        getAll={getMenuTree}
        rowSelection={false}
        pagination={false}
        ref={searchTablePageActionRef}
        permissionKey={PERMISSION_KEY_MENU}
        columns={[
          {
            title: '菜单 ID',
            dataIndex: 'id',
            hideInTable: true,
            hideInModal: true,
            hideInSearch: true,
          },
          {
            title: '菜单名称',
            dataIndex: 'name',
            showDetail: true,
            rules: [{ required: true }],
          },
          {
            title: '父菜单',
            dataIndex: 'parentId',
            valueType: 'treeSelect',
            allowClear: true,
            hideInSearch: true,
            hideInTable: true,
            fieldProps: {
              fieldNames: {
                value: 'id',
                label: 'name',
              },
            },
            request: async () => {
              const res = await getMenuTree();
              if (checkRespSuccessful(res)) {
                return res.data
                  ? [
                      {
                        name: '根菜单',
                        id: 0,
                        children: res.data,
                      },
                    ]
                  : [];
              }
              return [];
            },
          },
          {
            title: '菜单类型',
            dataIndex: 'type',
            valueType: 'tag',
            hideInSearch: true,
            rules: [{ required: true }],
            valueEnum: initialState?.system_menu_type?.tagValueEnum,
            options: initialState?.system_menu_type?.numOptions,
          },
          {
            title: '路由地址',
            dataIndex: 'path',
            hideInSearch: true,
          },
          {
            title: '权限标识',
            dataIndex: 'permission',
            hideInSearch: true,
          },
          {
            title: '显示顺序',
            dataIndex: 'sort',
            hideInSearch: true,
            hideInTable: true,
            rules: [{ required: true }],
          },
          {
            title: '菜单图标',
            dataIndex: 'icon',
            hideInSearch: true,
          },
          // {
          //   title: '组件名',
          //   dataIndex: 'component',
          //   hideInSearch: true,
          //   hideInTable: true,
          // },
          {
            title: '状态',
            dataIndex: 'status',
            valueType: 'select',
            valueEnum: initialState?.system_common_status?.valueEnum,
            options: initialState?.system_common_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
          },
          {
            title: '是否可见',
            dataIndex: 'visible',
            valueType: 'select',
            hideInSearch: true,
            hideInTable: true,
            valueEnum: initialState?.system_common_visible_status?.valueEnum,
            options: initialState?.system_common_visible_status?.numOptions,
            rules: [{ required: true, message: '请选择状态' }],
          },
          // {
          //   title: '是否缓存',
          //   dataIndex: 'keepAlive',
          //   valueType: 'select',
          //   hideInSearch: true,
          //   hideInTable: true,
          //   valueEnum: initialState?.system_menu_keep_alive_status?.valueEnum,
          //   options: initialState?.system_menu_keep_alive_status?.numOptions,
          //   rules: [{ required: true, message: '请选择' }],
          // },
          // {
          //   title: '是否总是显示',
          //   dataIndex: 'alwaysShow',
          //   valueType: 'select',
          //   hideInSearch: true,
          //   hideInTable: true,
          //   valueEnum: initialState?.system_common_whether_status?.valueEnum,
          //   options: initialState?.system_common_whether_status?.numOptions,
          //   rules: [{ required: true, message: '请选择' }],
          // },
        ]}
        toolBarRender={(nodes) => {
          return [
            ...nodes,
            <Access
              key="multipleAdd"
              accessible={true || access.permissionFilter('system:menu:multipleAdd')}
            >
              <Button
                onClick={() => {
                  setModalOpen(true);
                }}
                type="primary"
              >
                批量新增按钮权限
              </Button>
            </Access>,
          ];
        }}
        showExpandableAllBtn
      />
      {modalOpen && (
        <ModalForm
          title="批量新增按钮权限"
          width={600}
          layout="horizontal"
          labelCol={{ span: 5 }}
          open={modalOpen}
          omitNil
          isKeyPressSubmit
          onOpenChange={setModalOpen}
          onFinish={async ({ permissionPrefix, namePrefix, parentId, types }) => {
            const hide = message.loading(`正在批量新增按钮权限`);
            try {
              let prefixEnd: string = permissionPrefix;
              if (!prefixEnd) {
                const getMenuRes = await getMenuList();
                if (!checkRespSuccessful(getMenuRes)) {
                  message.error(`批量新增按钮权限失败，后台响应：${getMenuRes.message}，请重试`);
                  hide();
                  return;
                }
                prefixEnd = findMenuPath(parentId, getMenuRes.data || []).join(':') + ':';
              }

              let failFlag = false;
              for (let i = 0, limit = types.length; i < limit; i++) {
                const type = types[i];
                const addMenuParams = {
                  name:
                    initialState?.system_permission_action_type?.valueEnum[type].text + namePrefix,
                  permission: prefixEnd + type,
                  sort: i + 1,
                  parentId,
                  status: 0,
                  visible: 0,
                  type: 3,
                };
                const res = await addMenu(addMenuParams as API.Menu);
                if (!checkRespSuccessful(res)) {
                  failFlag = true;
                }
              }
              hide();
              if (!failFlag) {
                message.success(`批量新增按钮权限成功`);
                setModalOpen(false);
                searchTablePageActionRef.current?.refresh();
              } else {
                message.error(`批量新增按钮权限时，可能部分操作失败，请重试`);
              }
            } catch (error) {
              hide();
              message.error(`批量新增按钮权限失败，请重试`);
            }
          }}
        >
          <ProFormText
            name="permissionPrefix"
            label="权限标识前缀"
            placeholder="默认根据父级 path 生成，如：system:dict:"
          />
          <ProFormText name="namePrefix" label="菜单名称前缀" placeholder="默认为空，如：字典" />
          <ProFormTreeSelect
            name="parentId"
            label="父菜单"
            allowClear
            rules={[{ required: true, message: '请选择' }]}
            secondary
            fieldProps={{
              fieldNames: {
                label: 'name',
                value: 'id',
              },
            }}
            request={async () => {
              const res = await getMenuTree();
              if (checkRespSuccessful(res)) {
                return res.data
                  ? [
                      {
                        name: '根菜单',
                        id: 0,
                        children: res.data,
                      },
                    ]
                  : [];
              }
              return [];
            }}
          />
          <ProFormSelect
            name="types"
            label="权限类型"
            mode="multiple"
            rules={[{ required: true, message: '请选择' }]}
            options={initialState?.system_permission_action_type?.options}
          />
        </ModalForm>
      )}
    </>
  );
};

export default Menu;
